<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<el-form ref="discountDialogFormRef" :model="state.ruleForm" size="default" label-width="150px">
				<el-form-item label="活动名称" prop="couponName" :rules="{ required: true, message: '活动标题不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.couponName" placeholder="请输入优惠券名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="优惠券备注" prop="remark">
					<el-input v-model="state.ruleForm.remark" placeholder="请输入活动名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="卷类型" prop="couponType">
					<el-radio-group v-model="state.ruleForm.couponType" :disabled="state.couponTypeDisabled">
						<el-radio :label="0">满减券</el-radio>
						<el-radio :label="1">折扣券</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item>
					<div class="acitivty-rule">
						<!-- <el-form label-position="left" ref="couponTypeFormRef" :model="state.ruleForm.couponDiscountContent"> -->
						<div class="activity-rule-content">
							<!-- <el-form-item label=""> -->
							<el-row :gutter="5" v-if="state.ruleForm.couponType == 0">
								<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item
										label="消费满"
										prop="couponDiscountContent.buy"
										:rules="{ required: true, message: '消费满多少元不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponDiscountContent.buy" type="number" step="0.1" min="0" clearable>
											<template #append>
												<div>元</div>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item
										label="立减"
										prop="couponDiscountContent.discount"
										:rules="{ required: true, message: '消费立减元不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponDiscountContent.discount" type="number" step="0.1" min="0" clearable>
											<template #append> 元</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="5" v-else>
								<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item
										label="消费满"
										prop="couponDiscountContent.buy"
										:rules="{ required: true, message: '消费满多少元不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponDiscountContent.buy" type="number" step="0.1" min="0">
											<template #append>
												<div>元</div>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item
										label="打"
										prop="couponDiscountContent.discount"
										:rules="{ required: true, message: '消费满多少元打折为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponDiscountContent.discount" type="number" step="0.1" min="0.1" max="10">
											<template #append> 折</template>
										</el-input>
									</el-form-item>
								</el-col>

								<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item label="最多优惠" label-width="80px">
										<el-input v-model="state.ruleForm.couponDiscountContent.maxDiscount" type="number" max="100" step="0.1" min="0">
											<template #append> 元</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<!-- </el-form-item> -->
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>

				<el-form-item label="发券总量" prop="totalQuantity" :rules="{ required: true, message: '发券总量能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.totalQuantity" placeholder="请输入发券总量" type="number" clearable>
						<template #append>
							<div>张</div>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item label="每人限领次数" prop="userCollectTimes" :rules="{ required: true, message: '每人限领次数不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.userCollectTimes" placeholder="请输入每人限领次数" clearable>
						<template #append>
							<div>张</div>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item label="领券时间" prop="collectTime" :rules="{ required: true, message: '领券时间不能为空', trigger: 'blue' }">
					<el-date-picker
						v-model="state.ruleForm.collectTime"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</el-form-item>

				<el-form-item label="卷有效期" prop="validPeriodType">
					<el-radio-group v-model="state.ruleForm.validPeriodType" :disabled="state.validPeriodTypeDisabled">
						<el-radio :label="0">相对天数</el-radio>
						<el-radio :label="1">固定区间</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item>
					<div class="acitivty-rule">
						<!-- <el-form label-position="left" :model="state.ruleForm.couponValidPeriod" ref="validPeriodTypeFormRef"> -->
						<div class="activity-rule-content">
							<!-- <el-form-item label=""> -->
							<el-row :gutter="5" v-if="state.ruleForm.validPeriodType == 0">
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
									<el-form-item
										label="领券"
										prop="couponValidPeriod.collectCouponDays"
										:rules="{ required: true, message: '领券生效时间不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponValidPeriod.collectCouponDays" type="number" min="1">
											<template #append>
												<div>天后生效</div>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
									<el-form-item
										label="有效期"
										prop="couponValidPeriod.effectiveDays"
										:rules="{ required: true, message: '领券有效期不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-input v-model="state.ruleForm.couponValidPeriod.effectiveDays" type="number" min="1">
											<template #append> 天</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="5" v-else>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
									<el-form-item
										label="固定时间"
										prop="couponValidPeriod.fixTime"
										:rules="{ required: true, message: '领券固定时间不能为空', trigger: 'blue' }"
										label-width="80px"
									>
										<el-date-picker
											v-model="state.ruleForm.couponValidPeriod.fixTime"
											type="datetimerange"
											range-separator="至"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
										/>
									</el-form-item>
								</el-col>
							</el-row>
							<!-- </el-form-item> -->
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>
				<el-form-item label="优惠叠加" prop="offerStack">
					<el-switch
						v-model="state.ruleForm.offerStack"
						inline-prompt
						active-text="开启"
						inactive-text="关闭"
						:active-value="1"
						:inactive-value="0"
					/>
				</el-form-item>
				<el-form-item label="劵状态" prop="couponStatus">
					<el-radio-group v-model="state.ruleForm.couponStatus">
						<el-radio :label="0">公开发放</el-radio>
						<el-radio :label="1">后台发放</el-radio>
						<el-radio :label="2">禁止使用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="可用范围" prop="rangeType">
					<el-radio-group v-model="state.ruleForm.rangeType">
						<el-radio :label="0">全场通用</el-radio>
						<el-radio :label="1">指定商品可用</el-radio>
						<el-radio :label="2">指定商品不可用</el-radio>
						<!-- <el-radio :label="3">指定分类可用</el-radio> -->
					</el-radio-group>
				</el-form-item>

				<div class="activity-item" v-if="state.ruleForm.rangeType == 1 || state.ruleForm.rangeType == 2">
					<el-form-item>
						<el-button type="primary" link @click="addItem"> +添加商品</el-button>
					</el-form-item>
					<el-form-item>
						<div class="item-content">
							<div v-if="state.items.length > 0" class="flex item-header">
								<div class="content">商品信息</div>
								<div class="oper">操作</div>
							</div>
							<div>
								<div class="flex item-body" v-for="(item, index) in state.items">
									<div class="content flex">
										<div class="goods-img">
											<img :src="STATIC_URL + item.image" alt="" class="goods-img" />
										</div>
										<div class="goods-content">
											<div class="goods-title cursor-pointer" :title="item.goodsName">{{ item.title }}</div>
											<div class="goods-price">{{ item.price }}元</div>
										</div>
									</div>
									<div class="oper">
										<el-button type="danger" link @click="removeItem(index)"> 移除</el-button>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(discountDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</CustomDialog>
		<ItemDialog ref="ItemChoiceRef" @choice="choiceItem"></ItemDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { STATIC_URL } from '/@/utils/config';
import { CouponApi } from '/@/api/shop/coupon';

import _ from 'lodash';

const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/choice/index.vue'));
const ItemChoiceRef = ref();
const discountDialogFormRef = ref();
const validPeriodTypeFormRef = ref();

const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		couponName: '',
		couponType: 0,
		remark: '',
		validPeriodType: 0,
		couponValidPeriod: {
			startTime: '',
			endTime: '',
			collectCouponDays: '',
			effectiveDays: '',
			fixTime: [] as any,
		},
		couponDiscountContent: {
			buy: 0,
			discount: 0,
			maxDiscount: 0,
		},
		collectStartTime: '',
		collectEndTime: '',
		collectTime: [] as any,
		totalQuantity: 0,
		userCollectTimes: 0,
		rangeType: 0,
		couponStatus: 0,
		offerStack: 0, // 是否叠加使用
	},
	couponTypeDisabled: false,
	validPeriodTypeDisabled: false,
	items: [] as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// const rules = reactive<FormRules>({
// 	activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
// 	activityTime: [{ required: true, message: '请选择活动时间 ', trigger: 'blur' }],
// });

const onCancel = () => {
	closeDialog();
};

const choiceItem = (choiceGoodsItems: ChoiceGoodsItem[]) => {
	console.log('choiceGoodsItem: ', choiceGoodsItems);
	_.forEach(choiceGoodsItems, (choiceGoodsItem) => {
		state.items.push({
			id: choiceGoodsItem.id,
			image: choiceGoodsItem.image,
			title: choiceGoodsItem.title,
			price: choiceGoodsItem.price,
		});
	});
};

const removeItem = (index: number) => {
	state.items.splice(index, 1);
};

const addItem = () => {
	ItemChoiceRef.value.openDialog();
};
// 关闭弹窗
const closeDialog = () => {
	console.log('关闭窗口');
	state.dialog.isShowDialog = false;
	clearArraysContent();
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				const ids = state.items.map((e: any) => e.id);
				console.log('ids: ', ids);
				if (state.dialog.type === 'add') {
					await CouponApi().create({
						couponName: state.ruleForm.couponName,
						couponType: state.ruleForm.couponType,
						remark: state.ruleForm.remark,
						validPeriodType: state.ruleForm.validPeriodType,
						couponDiscountContent: state.ruleForm.couponDiscountContent,
						couponValidPeriod: {
							startTime: state.ruleForm.validPeriodType == 0 ? '' : state.ruleForm.couponValidPeriod.fixTime[0].getTime(),
							endTime: state.ruleForm.validPeriodType == 0 ? '' : state.ruleForm.couponValidPeriod.fixTime[1].getTime(),
							collectCouponDays: state.ruleForm.couponValidPeriod.collectCouponDays,
							effectiveDays: state.ruleForm.couponValidPeriod.effectiveDays,
						},
						collectStartTime: state.ruleForm.collectTime[0].getTime(),
						collectEndTime: state.ruleForm.collectTime[1].getTime(),
						totalQuantity: state.ruleForm.totalQuantity,
						userCollectTimes: state.ruleForm.userCollectTimes,
						rangeType: state.ruleForm.rangeType,
						couponStatus: state.ruleForm.couponStatus,
						offerStack: state.ruleForm.offerStack,
						contentIds: ids,
					});
				} else {
					await CouponApi().update({
						id: state.ruleForm.id,
						couponName: state.ruleForm.couponName,
						couponType: state.ruleForm.couponType,
						remark: state.ruleForm.remark,
						validPeriodType: state.ruleForm.validPeriodType,
						couponDiscountContent: state.ruleForm.couponDiscountContent,
						couponValidPeriod: {
							startTime: state.ruleForm.validPeriodType == 0 ? '' : resolveTime(state.ruleForm.couponValidPeriod.fixTime[0]),
							endTime: state.ruleForm.validPeriodType == 0 ? '' : resolveTime(state.ruleForm.couponValidPeriod.fixTime[1]),
							collectCouponDays: state.ruleForm.couponValidPeriod.collectCouponDays,
							effectiveDays: state.ruleForm.couponValidPeriod.effectiveDays,
						},
						collectStartTime: resolveTime(state.ruleForm.collectTime[0]),
						collectEndTime: resolveTime(state.ruleForm.collectTime[1]),
						totalQuantity: state.ruleForm.totalQuantity,
						userCollectTimes: state.ruleForm.userCollectTimes,
						rangeType: state.ruleForm.rangeType,
						couponStatus: state.ruleForm.couponStatus,
						offerStack: state.ruleForm.offerStack,
						contentIds: ids,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				msg().error('操作失败');
			}
		}
	});
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.dialog.title = '修改优惠券活动';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		console.log('id: ', id);
		clearArraysContent();
		const { data } = await CouponApi().view(id);
		state.ruleForm.id = id;
		console.log('data: ', data);
		state.ruleForm.couponName = data.couponName;
		state.ruleForm.couponType = data.couponType;
		state.ruleForm.remark = data.remark;
		state.ruleForm.validPeriodType = data.validPeriodType;
		state.ruleForm.totalQuantity = data.totalQuantity;
		state.ruleForm.userCollectTimes = data.userCollectTimes;
		state.ruleForm.rangeType = data.rangeType;
		state.ruleForm.couponStatus = data.couponStatus;
		state.ruleForm.offerStack = data.offerStack;
		state.ruleForm.couponValidPeriod = data.couponValidPeriodVO;
		if (data.validPeriodType == 1) {
			state.ruleForm.couponValidPeriod.fixTime = [data.couponValidPeriodVO.startTime, data.couponValidPeriodVO.endTime];
		}
		state.ruleForm.couponDiscountContent = data.discountContentVO;
		state.ruleForm.collectTime = [data.collectStartTime, data.collectEndTime];
		if (data.rangeType != 0) {
			state.items = data.activityItems;
			console.log('state.items: ', state.items);
		}
		state.couponTypeDisabled = true;
		state.validPeriodTypeDisabled = true;
	} else {
		state.dialog.title = '新增优惠券活动';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
		state.couponTypeDisabled = false;
		state.validPeriodTypeDisabled = false;
	}
	state.dialog.isShowDialog = true;
};

const resolveTime = (time: any) => {
	const contentType = typeof time;

	if (contentType == 'string') {
		console.log('time: ', time, ' is string: ', new Date(time).getTime());
		return new Date(time).getTime();
	}
	return time.getTime();
};

const clearArraysContent = () => {
	state.items = [];
	state.ruleForm.collectTime = [];
	state.ruleForm.couponValidPeriod = {
		startTime: '',
		endTime: '',
		collectCouponDays: '',
		effectiveDays: '',
		fixTime: [] as any,
	};
	state.ruleForm.couponDiscountContent = {
		buy: 0,
		discount: 0,
		maxDiscount: 0,
	};

	state.ruleForm.couponName = '';
	state.ruleForm.couponType = 0;
	state.ruleForm.remark = '';
	state.ruleForm.validPeriodType = 0;
	state.ruleForm.totalQuantity = 0;
	state.ruleForm.userCollectTimes = 0;
	state.ruleForm.rangeType = 0;
	state.ruleForm.couponStatus = 0;
	state.ruleForm.offerStack = 0;
};
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}

.content {
	flex: 1;
}

.oper {
	width: 60px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;

	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}

	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}
</style>
